
/**
 * author shwj 20180502
 */
var schoolId = window.location.href.queryURLParameter('schoolId').schoolId; // schoolId

function init() {
    try {
        window.vipObj = vipObj; // 全局下面设置vipObj方法
    } catch (error) {
        // 
    }
}
init();

/*
    <div class="eschool-build-wrapper">
            <img src="images/jianshe@2x.png" alt="">
            <span>数据正在创建中...</span>
        </div>
    </div>
*/

var indexRender = (function() {
    // 
    var INDEX_API = PRE_API + '/edu/eCampus/getCampusFrame', // 接口地址
        $content = $('.content'),
        $eschoolBuild = $('.eschool-build'),
        $loadingIconWrapper = $('.loading-icon-wrapper'),
        $tips = $('.tips');
    

    var carsouelRender = function(json) {
        var $compStr = $('<div class="comp-container comp-carousel">');
        var $compWrapperContent = $('<div class="comp-content">');
        var $compStrWrapper = $('<div class="swiper-wrapper">');
        $compWrapperContent.append($compStrWrapper);
        var itemStr = '';
        var arrCarouselImg = json['carouselImg'];
        $.each(arrCarouselImg, function(index, item) {
            var tempJson = item;
            // data-srcset="' + tempJson.pic +'"
            var linkUrl = createLink(tempJson);
            // if (tempJson.article.artId && tempJson.article.cateId) {
            //     linkUrl = 'about.html?articleId=' + tempJson.article.artId
            // } else if(tempJson.article.cateId) {
            //     linkUrl = 'list.html?cateId=' + tempJson.article.cateId + '&schoolId=' + schoolId
            // }
            itemStr += '<div class="swiper-slide"><a href="' + (linkUrl ? linkUrl : 'javascript:;' ) +'"><img data-src="' + (tempJson.pic) +'" class="swiper-lazy swiper-lazy-preloader-white"/><div class="swiper-lazy-preloader"></div></a></div>';
        });
        
        $compStrWrapper.append(itemStr);
        $compStr.append('<div class="swiper-pagination"></div>')
        $compStr.append($compStrWrapper)
        return $compStr.append($compStr);
    }
    // 设置跳转链接
    function bindLinkEvent(json) {
        if (window.vipObj) {
            window.vipObj.getClickItemData(JSON.stringify(json));
        }
    }

    var menusRender = function(json) {
        // onclick="bindLinkEvent("' + JSON.stringify({ typeName: tempJson['sName'], url: undefined}) +'")"
        var $compStr = $('<div class="comp-container comp-menus">');
        var $compStrWrapper = $('<div class="cp-item-content">');
        var itemStr = '';
        for (var i = 0; i < json['menusList'].length; i++) {
            var tempJson = json['menusList'][i];
            
            var linkUrl = createLink(tempJson);
            itemStr += '<div class="menus-item menus-flex' + json['column'] + '-width" data-catename="' + tempJson['sName'] +'" data-linkurl="'+ linkUrl +'"><a href="javascript:;" ><div class="u-icon-img"><img src="' + tempJson.sPic + '"></div><span>' + tempJson['sName'] +'</span></a></div>';
        }
        $compStrWrapper.html(itemStr);
        $compStr.on('click', '.menus-item', function() {
            var bindData = { cateName: $(this).data('catename'), url: $(this).data('linkurl') };
            if (bindData.url) {
                var toUrl = bindData.url + (bindData.url.indexOf('?') > -1?'&':'?') + 'cateName=' + encodeURIComponent(bindData.cateName);
                window.location.href = toUrl;
                bindLinkEvent(bindData);
            }
        });
        return $compStr.append($compStrWrapper);
    }

    function createLink(tempJson) {
        var linkUrl = '';
        if (tempJson.article.cateId || tempJson.article.artId) {
            if (tempJson.article.artId) {
                var articleLink = getArticleLink(tempJson.article.artId);
                if(articleLink) {
                    linkUrl = articleLink;
                }
                else {
                    linkUrl = 'about.html?articleId=' + tempJson.article.artId;
                }
            } else {
                linkUrl = 'list.html?schoolId=' + schoolId + '&cateId=' + tempJson.article.cateId;
            }
        }
        return linkUrl;
    }

    /**
     * 处理默认图片路径的问题
     * @param {*} pic 
     */
    function handlePicDefault(pic) {
        if(pic.indexOf('default') > -1) {
            return '.' + pic;
        }
        return pic;
    }
    /**
     * 图片渲染处理函数
     * @param {json} 图片json数据 
     */
    var picRender = function(json) {
        var $compStr = $('<div class="comp-container comp-pic">');
        var $compStrWrapper = $('<div class="cp-item-content">');
        var $img = $('<img data-src="'+ handlePicDefault(json.content) +'"/>');
        var itemStr = '';
        // var objImg = new Image();
        // objImg.src = json.content;
        // objImg.onload = function(e) {
        //     // console.log(objImg.width,'objImg');
        //     var viewWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
        //     var iHeigth = objImg.height * viewWidth / objImg.width;
        //     $compStrWrapper.height(iHeigth);
        // }
        // objImg.onerror = function(e) {
        //     // imgLoading(e)
        // }
        $img.attr('src', json.content);
        $compStrWrapper.append($img);
        $compStr.on('click', function(e) {
            e.preventDefault();
            if(createLink(json)) {
                window.location.href = createLink(json);
            }
        });
        return $compStr.append($compStrWrapper);
    }
    /**
     * 文本渲染处理函数
     * @param {json}
     */
    var textRender = function(json) {
        var $compStr = $('<div class="comp-container comp-text">');
        var $compStrWrapper = $('<div class="cp-item-content">');
        var itemStr = '<div style="color:'+ json['color'] +'; text-align:'+ json['align'] +';font-size:'+ json['textFontSize'] +'px">' + json.content + '</div>';
        $compStrWrapper.html(itemStr);
        $compStr.on('click', '.cp-item-content', function(e) {
            e.preventDefault();
            if(createLink(json)) {
                window.location.href = createLink(json);
            }
        })
        return $compStr.append($compStrWrapper);
    }

    var bindEvent = function() {
        var $swiperCarousel = $('.comp-carousel');
        $swiperCarousel.each(function(item, index) {
            var $slides = $(this).find('.swiper-slide');
            var swiperContainer = new Swiper(this, {
                pagination: {
                    el: '.swiper-pagination'
                },
                paginationClickable: true,
                loop: $slides.length > 1 ? true: false,
                speed: 600,
                autoplay: ($slides.length > 1 ? {
                    delay: 3000,
                    disableOnInteraction: false
                }: false),
                lazy: {
                    loadPrevNext: true
                }
            });
        })
        
    }

    var renderHtml = function(jsonArr) {

        for (var i = 0; i < jsonArr.length; i++) {
            var cur = jsonArr[i];
            if (cur.type == 'carousel') {
                $content.append(carsouelRender(cur));
            }
            if (cur.type == 'menus') {
                $content.append(menusRender(cur));
            }
            if (cur.type == 'pic') {
                $content.append(picRender(cur));
            }
            if (cur.type == 'text') {
                $content.append(textRender(cur));
            }
        }
        bindEvent();
    };

    var getPhoneData = function() {
        if(!schoolId) {
            $eschoolBuild.show();
            return;
        }
        $loadingIconWrapper.show();
        $.ajax({
            url: INDEX_API,
            type: 'post',
            dataType: 'json',
            headers: ajaxHeader(),  
            data: encrypt(JSON.stringify({
                "schoolId": schoolId
            })),
            timeout: 20000,
            cache: false,
            success: function (result) {
                $loadingIconWrapper.hide();
                // result.content.html 数据存在的时候返回
                // console.log(result&&result.content&&JSON.parse(result.content.html).length > 0);
                if (result&&result.content&&JSON.parse(result.content.html)&&JSON.parse(result.content.html).length > 0) {                 
                    var resHtml = JSON.parse(result.content.html);
                    // localStorage.setItem('PhoneData','' );
                    $eschoolBuild.hide();
                    renderHtml(resHtml);
                    var objSchoolData = { schoolMotto: result.content.schoolMotto, pic: result.content.pic };
                    if (window.vipObj) {
                        window.vipObj.geteshoolData(JSON.stringify(objSchoolData));
                    }
                    document.title = result.content.schoolName || 'e校园';
                }
                else {
                    $eschoolBuild.show();
                }
            },
            error: function(e) {
                $loadingIconWrapper.hide();
                $tips.find('span').html('加载失败，请重新加载').end().show();
                // onclick="window.location.reload()"
                $tips.on('click','.button-reload', function(){
                    if(isWeiXin()) {
                        window.location.href= window.location.href + '/' + Math.random()
                    }
                    else {
                        window.location.reload();
                    }
                    
                });
            }
        });
    };

    function isWeiXin(){
        var ua = window.navigator.userAgent.toLowerCase();
        if(ua.match(/MicroMessenger/i) == 'micromessenger'){
            return true;
        }else{
            return false;
        }
    }
    var getArticleLink = function(articleId) {
        var sLink = '';
        $.ajax({
            async: false,
            url: ARI_API + "/family/ecampus/getCampusArticle",
            type: 'post',
            dataType: 'json',
            headers: ajaxHeader(),  
            data: encrypt(JSON.stringify({
                "articleId": articleId
            })),
            cache: false
        }).done(function(res){
            if(res.status == 200&&res.content){
                if(res.content.sLink) {
                    sLink = res.content.sLink;
                }
            }
            else {
                sLink = '';
            }
        }).fail(function(e){
            console.log(e);
        });
        return sLink;
    }
    // 446758570784993280

    return {
        'init': function() {
            getPhoneData();
        }
    }

})();
// init
indexRender.init();